# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:30
# File     : main-v0.0.py
# Project  : codebuddy_craft
# Desc     : FastAPI主应用
# backend/main-v0.0.py
import os
import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
import uvicorn

from backend.api import code_routes, project_routes, chat_routes, websocket_routes
from backend.utils.config import get_settings
from backend.utils.cache import init_redis
from backend.database.connection import init_db, close_db
from backend.core.knowledge.vector_store import init_vector_store


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时初始化
    settings = get_settings()

    # 初始化数据库
    await init_db()

    # 初始化Redis缓存
    await init_redis()

    # 初始化向量存储
    await init_vector_store()

    print("🚀 CodeBuddy Craft 后端服务启动成功!")

    yield

    # 关闭时清理
    await close_db()
    print("👋 CodeBuddy Craft 后端服务已关闭")


def create_app() -> FastAPI:
    """创建FastAPI应用"""
    settings = get_settings()

    app = FastAPI(
        title="CodeBuddy Craft API",
        description="智能编程助手后端API",
        version="1.0.0",
        lifespan=lifespan
    )

    # 配置CORS
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["http://localhost:8501", "http://127.0.0.1:8501"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 注册路由
    app.include_router(code_routes.router, prefix="/api/code", tags=["代码生成"])
    app.include_router(project_routes.router, prefix="/api/projects", tags=["项目管理"])
    app.include_router(chat_routes.router, prefix="/api/chat", tags=["对话交互"])
    app.include_router(websocket_routes.router, prefix="/ws", tags=["实时通信"])

    # 静态文件服务
    app.mount("/static", StaticFiles(directory="static"), name="static")

    # 全局异常处理
    @app.exception_handler(Exception)
    async def global_exception_handler(request, exc):
        return JSONResponse(
            status_code=500,
            content={
                "code": 50001,
                "msg": f"服务器内部错误: {str(exc)}",
                "data": None
            }
        )

    # 健康检查
    @app.get("/health")
    async def health_check():
        return {"status": "healthy", "service": "CodeBuddy Craft API"}

    return app


app = create_app()

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )

